package com.tucy.logistics.modules.system.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.ObjectUtil;
import com.tucy.logistics.common.result.ServiceException;
import com.tucy.logistics.modules.system.captcha.service.SystemCaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * author: tcy
 * createDate: 2023/9/6
 * description: 验证码服务
 */
@Api(tags = "验证码")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    SystemCaptchaService captchaService;

    @ApiOperation(value = "验证码")
    @GetMapping("/normalCaptcha/{uuid}")
    public void captcha(HttpServletResponse response, @PathVariable("uuid") String uuid) throws IOException {
        /**
         * 圆形：CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(135,35,5,20);
         * 扭曲：ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(135,35,5,20);
         * 动图：GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(135,35,5);
         */
        // 定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(70, 32, 4, 10);
        // getCode()获取验证码
        String captchaCode = lineCaptcha.getCode();
        if (ObjectUtil.isNotEmpty(captchaCode)){
            captchaService.mathSaveCaptcha(captchaCode,uuid);
        }else {
            throw new ServiceException("验证码刷新失败");
        }
        // 图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }

    @ApiOperation(value = "运算验证码")
    @GetMapping("/mathCaptcha/{uuid}")
    public void mathCaptcha(HttpServletResponse response,@PathVariable("uuid") String uuid) throws IOException {
        // 这里定义的字符数无效，干扰元素有效
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(70, 32,1,10);
        // 自定义验证码内容为四则运算方式
        lineCaptcha.setGenerator(new MathGenerator());
        // 重新生成code
        lineCaptcha.createCode();
        // getCode()获取验证码
        String captchaCode = lineCaptcha.getCode();
        if (ObjectUtil.isNotEmpty(captchaCode)){
            captchaService.mathSaveCaptcha(captchaCode,uuid);
        }else {
            throw new ServiceException("验证码刷新失败");
        }
        // 图形验证码写出
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }
}
